﻿using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json;
using System.IO;
using System;
using System.Text;

public class IOMgr : MonoBehaviour
{

    string url = "";
    Dictionary<string, CustomConfig> dict_config = new Dictionary<string, CustomConfig>();
    public InputField customLevel;
    public InputField sumField;


    public void Save()
    {
        Debug.Log("$$$$$$$$Save");
        try
        {

            var drop = Drop.instance;
            int index = int.Parse(customLevel.text) - 1;
            var config = new CustomConfig();

            if (dict_config.ContainsKey(index.ToString()))
            {
                dict_config.Remove(index.ToString());
            }
            dict_config.Add(index.ToString(), config);

            config.level = index + 1;
            config.first = config.level == 1;
            config.sum = int.Parse(sumField.text);
            config.weight = drop.sumWeight;
            config.item_list = new Dictionary<string, float>();
            var items = drop.dict_items;
            foreach (var k in items.Keys)
            {

                var item = items[k];
                config.item_list[k] = item.slider.value;

            }

            if (url != "")
            {
                File.WriteAllText(url, JsonConvert.SerializeObject(dict_config));
            }
            else
            {
                FileOpenDialog pth = new FileOpenDialog();
                pth.structSize = System.Runtime.InteropServices.Marshal.SizeOf(pth);
                pth.filter = "json files\0*.json";
                pth.file = new string(new char[256]);
                pth.maxFile = pth.file.Length;
                pth.fileTitle = new string(new char[64]);
                pth.maxFileTitle = pth.fileTitle.Length;
                pth.initialDir = Application.dataPath;  // default path  
                pth.title = "保存配置文件";
                pth.defExt = "json";
                pth.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
                if (GetSaveFileName(pth))
                {
                    //sb.Clear();
                    //sb.Append(pth.file);

                    string filepath = pth.file;//选择的文件路径;  
                    File.WriteAllText(filepath, JsonConvert.SerializeObject(dict_config));
                    url = filepath;
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log(e);

            sb.Clear();
            sb.Append( e.Message + '\n' + e.StackTrace );
        }
    }

    StringBuilder sb = new StringBuilder();
    private void OnGUI()
    {
        GUI.Label(new Rect(0, 0, 300, 300), sb.ToString());
    }


    //链接指定系统函数       打开文件对话框
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] FileOpenDialog ofn);
    public static bool GetOFN([In, Out] FileOpenDialog ofn)
    {
        return GetOpenFileName(ofn);
    }

    //链接指定系统函数        另存为对话框
    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetSaveFileName([In, Out] FileOpenDialog ofn);
    public static bool GetSFN([In, Out] FileOpenDialog ofn)
    {
        return GetSaveFileName(ofn);
    }


    public void OpenFile()
    {
        FileOpenDialog dialog = new FileOpenDialog();

        dialog.structSize = Marshal.SizeOf(dialog);

        dialog.filter = "json files\0*.json\0All Files\0*.*\0\0";

        dialog.file = new string(new char[256]);

        dialog.maxFile = dialog.file.Length;

        dialog.fileTitle = new string(new char[64]);

        dialog.maxFileTitle = dialog.fileTitle.Length;

        dialog.initialDir = UnityEngine.Application.dataPath;  //默认路径

        dialog.title = "Open File Dialog";

        dialog.defExt = "json";//显示文件的类型
        //注意一下项目不一定要全选 但是0x00000008项不要缺少
        dialog.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;  //OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR

        if (DialogShow.GetOpenFileName(dialog))
        {

            var content = File.ReadAllText(dialog.file);

            try
            {
                url = dialog.file;
                var config = JsonConvert.DeserializeObject<Dictionary<string, CustomConfig>>(content);
                dict_config = config;

                //加载第一个关卡
                if (!config.ContainsKey("0"))
                {
                    CustomConfig t = new CustomConfig();
                    t.level = 1;
                    t.item_list = new Dictionary<string, float>();
                    config["0"] = t;
                }
                LoadConfig(config["0"]);
            }
            catch (Exception e)
            {
                Debug.Log(e);
            }

        }
    }

    private void LoadConfig(CustomConfig c)
    {
        var drop = Drop.instance;
        foreach (var key in drop.dict_items.Keys)
        {
            var item = drop.dict_items[key];
            GameObject.Destroy(item.gameObject);
        }
        drop.dict_items.Clear();


        customLevel.text = c.level.ToString();
        foreach (var k in c.item_list.Keys)
        {
            var w = c.item_list[k];
            drop.AddItem(k);
            drop.dict_items[k].SetValue(w);

        }
        drop.refreshWeight();
    }

    string lastCustom = "1";
    public void onChangeCustom()
    {
        try
        {
            if (customLevel.text != lastCustom)
            {
                Debug.Log("$$$$$$$$切换关卡");
                lastCustom = customLevel.text;
                int index = int.Parse(customLevel.text) - 1;
                if (!dict_config.ContainsKey(index.ToString()))
                {
                    CustomConfig t = new CustomConfig();
                    t.level = int.Parse(lastCustom);
                    t.item_list = new Dictionary<string, float>();
                    dict_config.Add(index.ToString(), t);
                }
                LoadConfig(dict_config[index.ToString()]);
            }
        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
    }


    public void Load()
    {
        Debug.Log("$$$$$$$$$Load");
        OpenFile();
    }
}



[Serializable]
class CustomConfig
{
    public int level { get; set; }
    public int sum { get; set; }
    public bool first { get; set; }
    public float weight { get; set; }
    public Dictionary<string, float> item_list { get; set; }
}